const version = '7.73';
const baseUrl = `https://developer.api.autodesk.com/modelderivative/v2/viewers/${version}/`; // https://developer.api.autodesk.com/modelderivative/v2/viewers/7.73/
const savePath = `./developer.api.autodesk.com/modelderivative/v2/viewers/${version}/`;

const axios = require('axios');
const fs = require('fs');
const path = require('path');
const url = require('url');
const { basicfiles } = require('./data/basicFiles'); // 基础文件
const { externalExtensions } = require('./data/externalExtensions'); // 所有插件文件
const { languages } = require('./data/languages'); // 所有插件文件
const { lightsPresets } = require('./data/lightsPresets'); // 所有插件文件
const { logger } = require('./utils/Logger4j');
const { sleep } = require('./utils/threadSleep');

const allFiles = [
    ...basicfiles,
    ...externalExtensions,
    ...languages,
    ...lightsPresets,
]

// console.log('需要下载的文件', allFiles, allFiles.length);

const requestConfig = { responseType: 'stream', timeout: 10000 };

/** 下载文件并写入本地磁盘 */
function downloadAndSaveFile(baseUrl, relativeUrl, savePath) {

    const httpUrl = url.resolve(baseUrl, relativeUrl);
    const hardDiskSaveLoad = path.join(savePath, relativeUrl);
    // console.log(httpUrl, hardDiskSaveLoad);

    axios
        .get(httpUrl, requestConfig)
        .then((response) => {
            if (response.status !== 200) {
                logger.error(httpUrl);
                logger.error(
                    `文件下载失败, ` +
                        response.status ? `response: ${response.status}` : ''
                );
                return;
            }
            const loadToFile = hardDiskSaveLoad.slice(0, hardDiskSaveLoad.lastIndexOf('\\'));
            if (!fs.existsSync(loadToFile)) { fs.mkdirSync(loadToFile, { recursive: true }); }
            response.data.pipe(fs.createWriteStream(hardDiskSaveLoad));
            logger.debug(httpUrl);
            logger.debug('文件下载成功');
        })
        .catch((error) => {
            logger.error(httpUrl);
            const errorJOBJ = { error: error.code, message: error.message, response: '' };
            if (error.response) { errorJOBJ.response = error.response.status + ' ' + error.response.statusText; }
            logger.error('错误 ' + JSON.stringify(errorJOBJ));
        });
}


async function downLoadForge(baseUrl, savePath, allFiles) {

    // 请求&保存文件

    for (let i = 0; i < allFiles.length; i++) {
        const fileRelativeUrl = allFiles[i];
        // if (i > 0) return; // 单件调试
        downloadAndSaveFile(baseUrl, fileRelativeUrl, savePath);
        await sleep(100);

        if (fileRelativeUrl.endsWith('.js')) {
            const fileRelativeUrl_withoutSuffix = fileRelativeUrl.slice(0, fileRelativeUrl.length - 3);

            const fileRelativeUrl_jsmap = fileRelativeUrl_withoutSuffix + '.js.map';
            downloadAndSaveFile(baseUrl, fileRelativeUrl_jsmap, savePath);
            await sleep(100);

            const fileRelativeUrl_mjs = fileRelativeUrl_withoutSuffix + '.min.js';
            downloadAndSaveFile(baseUrl, fileRelativeUrl_mjs, savePath);
            await sleep(100);

            const fileRelativeUrl_mjsmap = fileRelativeUrl_withoutSuffix + '.min.js.map';
            downloadAndSaveFile(baseUrl, fileRelativeUrl_mjsmap, savePath);
            await sleep(100);
        }
    }
}

downLoadForge(baseUrl, savePath, allFiles);